package com.platform.validator;

import com.platform.comm.util.CryptUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description:手机验证器
 *
 * @author lx
 */
public class MobileValidate implements ConstraintValidator<Mobile, String> {

    Pattern p = Pattern.compile("^((0\\d{3,4}-\\d{7,8})|(1[35874]\\d{9}))$");

    /**
     * 固定电话
     */
    Pattern fixed = Pattern.compile("^((0\\d{3,4}-\\d{7,8}))$");

    @Override
    public void initialize(Mobile constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(StringUtils.isBlank(value)){
          return true;
        }
        if(value.length() > 11){
            try{
                Matcher f = fixed.matcher(value);
                if (f.matches()) {
                    return f.matches();
                }
                value = CryptUtil.bs64DecryptWithHead(value);
                Matcher m = p.matcher(value);
                return m.matches();
            }catch (Exception e){
                return false;
            }
        }else{
            Matcher m = p.matcher(value);
            return m.matches();
        }
    }



}
